import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

var car = JSON.parse(localStorage.getItem("car") || "[]");
export default new Vuex.Store({
  state: {
    // count:112,
    msg: "hello  world",

    car: car
  },
  mutations: {
    // aa(state,obj){
    //   console.log(obj,111);
    //   state.count++;
    // }

    /* 接受加入至购物车的数据 */
    addToCar(state, obj) {
      var flag = false;
      console.log(obj, 6677);
      state.car.some(item => {
        if (item.id == obj.id) {
          item.count += parseInt(obj.count);
          flag = true;
          return true;
        }
      })
      if (!flag) {
        state.car.push(obj);
      }

      localStorage.setItem("car", JSON.stringify(state.car))
    },

    /* 改变数量 */
    changeCount(state,num){
    console.log(num,65);
    state.car.forEach(item=>{
      if(item.id==num.id){
        item.count=num.count
      }
    })
    localStorage.setItem("car", JSON.stringify(state.car))

    },

    /* 删除 */
    del(state,id){
      state.car.some((item,i)=>{
        if(item.id==id){
          state.car.splice(i,1);
          return  true;
        }
       
      })
      localStorage.setItem("car", JSON.stringify(state.car))
    },

    /* 状态管理 */
    selectedChanged(state,info){
      console.log(info,676);
      state.car.some((item,i)=>{
        if(item.id==info.id){
          item.selected=info.val;
          return  true;
        }
       
      })
      localStorage.setItem("car", JSON.stringify(state.car))
      
    }
  },
  getters: {
    // "bb":function(state){
    //   return  state.count++;
    // }

    getAllCount(state) {
      var c = 0;
      state.car.forEach(item => {
        c += item.count;
      });
      return c;
    },

    /* 获取numberbox中的数量===即商品数量 */
    getNum(state) {
      var obj = {};
      state.car.forEach(item => {
        obj[item.id]=item.count
      });
      return obj;
    },


    getSelect(state) {
      var selectObj = {};
      state.car.forEach(item => {
        selectObj[item.id]=item.selected;
        // ======{88:true,89:false}
      });
      return selectObj;
    },

    /* 计算总计+数量 */
    getSum(state){
      var  num=0;
      var  total=0;
      state.car.forEach(item => {
        if(item.selected){
          num+=item.count;
          total+=item.count*item.price;
        }
      });
      return  {num,total}
    }
  },
})